import aiohttp
import json
from typing import Callable

class HttpMgr:
    
    _instance = None
    _BASE_URL = "https://time.running8.com/api/echarts"
    _AUTH_TOKEN = "3717/bMtH1kUQcUY4seXpCeLXXyw0okFTCrDL"

    def __new__(cls):
        if not cls._instance:
            cls._instance = super().__new__(cls)
            cls._instance._callbacks = []
            cls._instance.device_cache = {}
        return cls._instance

    def add_callback(self, callback):
        self._callbacks.append(callback)

    def remove_callback(self, callback):
        self._callbacks.remove(callback)

    @classmethod
    async def IenumLoginWS(cls, cid: str):
        url = f"{HttpMgr._BASE_URL}/webSocket/init/{cid}/{HttpMgr._AUTH_TOKEN}"
        async with aiohttp.ClientSession() as session:
            try:
                async with session.get(url) as response:
                    if response.status == 200:
                        result = await response.text()
                        print(f"[INFO] LoginWS response: {result}")
            except Exception as e:
                print(f"Request failed: {str(e)}")

    @staticmethod
    async def RefreshDeviceInfo():
        #url = f"{HttpMgr._BASE_URL}/score-configs/{HttpMgr._AUTH_TOKEN}"
        url = "http://localhost:8764"
        print("调用了http init")
        await HttpMgr._handle_score_configs(url, "刷新出错")

    @staticmethod
    async def GetDeviceInfo(callback: Callable):
        url = f"{HttpMgr._BASE_URL}/score-configs/{HttpMgr._AUTH_TOKEN}"
        await HttpMgr._handle_score_configs(url, "启动出错", callback)

    @staticmethod
    async def _handle_score_configs(url: str, error_msg: str, callback: Callable = None):
        async with aiohttp.ClientSession() as session:
            try:
                async with session.get(url) as response:
                    if response.status == 200:
                        data = await response.json()
                        print(f"[INFO] {error_msg.replace('出错', '成功')}: {data}")
                        
                        HttpMgr._instance.device_cache = {
                            item['score_type']: [str(mac) for mac in item['mac']]
                            for item in data["score_configs"]
                        }
                        
                        for callback in HttpMgr._instance._callbacks:
                            await callback(HttpMgr._instance.device_cache)
                        
                    else:
                        print(f"[ERROR] {error_msg}: {await response.text()}")
            except Exception as e:
                print(f"[ERROR] {error_msg}: {str(e)}")

# 使用示例
async def main():
    # 刷新设备信息
    await HttpMgr.RefreshDeviceInfo()
    
    # 获取设备信息并回调
    async def callback():
        print("Device info updated!")
    await HttpMgr.GetDeviceInfo(callback)

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())
